from pyjenkinsci.jenkinsobject import jenkinsobject
from pyjenkinsci.job import job

class view( jenkinsobject ):

    def __init__( self, url, name, hudson ):
        self.name = name
        self.hudson = hudson
        jenkinsobject.__init__( self, url )
        
    def __str__(self):
        return self.name
    
    def __getitem__(self, str_job_id ):
        assert isinstance( str_job_id, str )
        jobdict = self.getJobDict()
        api_url = self.python_api_url( self.getJobURL( str_job_id ) )
        return job( api_url, str_job_id, self.hudson )
        
    def keys(self):
        return self.getJobDict().keys()
    
    def iteritems(self):
        for name, url in self.getJobDict().iteritems():
            api_url = self.python_api_url( url )
            yield name, job( api_url, name, self.hudson )
    
    def values(self):
        return [ a[1] for a in self.iteritems() ]
    
    def items(self):
        return [ a for a in self.iteritems() ]
    
    def _getJobs( self ):        
        if not self._data.has_key( "jobs" ):
            pass
        else:
            for viewdict in self._data["jobs"]:
                yield viewdict["name"], viewdict["url"]
                
    def getJobDict(self):
        return dict( self._getJobs() )
    
    def __len__(self):
        return len( self.getJobDict().keys() )
    
    def getJobURL( self, str_job_name ):
        try:
            job_dict = self.getJobDict()
            return job_dict[ str_job_name ]
        except KeyError, ke:
            all_views = ", ".join( job_dict.keys() )
            raise KeyError("Job %s is not known - available: %s" % ( str_job_name, all_views ) )
    
    def getHudsonObject(self):
        return self.hudson
    
    def id(self):
        """
        Calculate an ID for this object.
        """        
        return "%s.%s" % ( self.className, self.name )
